import React from 'react';
import { connect } from 'dva';
import { Card, Button, Form, Input, Row, Col, Select, message,Spin, Table, Divider,Popconfirm} from 'antd';
import styles from './index.less';
import router from 'umi/router';
import Extension from './extension';


const FormItem = Form.Item;
const { Option } = Select;

@Form.create()
class CouponComponent extends React.Component {
    constructor() {
        super();
        this.state={
            dataSource:[],
            loading: true,
            btnLoading: false,
            valueLoading: false,
            paginationProps: {
                showSizeChanger: true,
                showQuickJumper: false,
                showTotal: total => `共 ${total} 条记录`,
                pageSize: 10,
                total: 0,
                pageIndex: 1,
              },
        }
    }

    componentWillMount() {
      window.Isoption = false;
    }

    componentDidMount() {
      window.Isoption = true;
        this.requestCouponList()
    }

    addCoupon=() => {
        router.replace({
            pathname: `/${window.storeId}/marketing/coupon/add`
        })
    }

    clickEdit=(Id)=> {
        router.replace({
            pathname: `/${window.storeId}/marketing/coupon/edit/${Id}`
        })
    }

    requestCouponList =(params) => {
        const { dispatch} = this.props;
        const { paginationProps: { pageIndex, pageSize }} = this.state;
        dispatch({
            type: 'marketing/GetCouponsListWithPage',
            payload: {
                PageIndex: pageIndex, //页码
                PageSize: pageSize, //页数
                Name: params&& params.Name?params.Name:'',
                Status: params&& params.Status?params.Status:0
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            paginationProps: {
                                ...this.state.paginationProps,
                                total: res.Data.Total
                            },
                            dataSource: res.Data?res.Data.DataList:[],
                            loading: false,
                            btnLoading: false,
                            valueLoading: false
                        })
                    }
                },
                error: res=> {
                    console.log(res.Msg)
                }
            }
        })
    }

    handleSearch =e => {
        e.preventDefault();
        const {form} = this.props;
        this.setState({
            btnLoading: true,
            valueLoading: true,
        })
        form.validateFields((err, values) => {
            if(err) return;
            const datas = {
                ...values,
            }
            this.setState({
                formValues: datas
            })
            this.requestCouponList({...datas})
        })
    }

    handleFormReset =()=> {
        const { form } = this.props;
        form.resetFields();
    }

    onTableChange =(pagination)=> {
        let {paginationProps, formValues} = this.state;
        let data = {
            ...paginationProps,
            pageIndex: pagination.current,
            pageSize: pagination.pageSize,
        };
        this.setState({
            paginationProps: data,
            formValues,
            valueLoading: true,
        }, ()=> {
            this.requestCouponList({...formValues})
        })
    }

    // 删除
    delete =(Id) => {
        const { dispatch} = this.props;
        dispatch({
            type: 'marketing/DelCoupon',
            payload: {
                Id: Id
            },
            callBack: {
                success: res=> {
                    if(res.Code ===0) {
                        message.success('删除成功');
                        this.setState({
                            valueLoading: true
                        }, ()=> {
                            this.requestCouponList()
                        })
                    }
                },
                error: res=> {
                    message.error(res.Msg)
                }
            }
        })
    }

    // 推广
    clickExtension =(Id, data)=> {
        const title="推广活动";
        const width=400;
        this.extension.show({width,title, Id, data})
    }

    renderForm() {
        const {
          form: { getFieldDecorator },
        } = this.props;
        const {btnLoading} = this.state;

        return (
          <Form  layout="inline">
            <Row >
              <Col span={8}>
                <FormItem label="优惠券名称">
                  {getFieldDecorator('Name')(
                    <Input className="xkd-width-per-100" />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="优惠券状态">
                  {getFieldDecorator('Status',{
                    initialValue:0
                  })(
                    <Select placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>全部</Option>
                      <Option value={1}>进行中</Option>
                      <Option value={2}>已结束</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <div style={{ overflow: 'hidden' }}>
              <div className="screenNavButton">
                <Button type="primary" onClick={this.handleSearch} loading={btnLoading}>
                  筛选
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
              </div>
            </div>
          </Form>
        );
      }

    render() {
        const columns = [
            {
                title: '优惠券名称',
                dataIndex: 'Name',
                key: 'Name',
            },
            {
                title: '优惠内容',
                dataIndex: 'FormativeContext',
                key: 'FormativeContext',
            },
            {
                title: '有效时间',
                dataIndex: 'Valied',
                key: 'Valied',
            },
            {
                title: '已领取/剩余',
                dataIndex: 'TotalTake/TotalSurplus',
                key: 'TotalTake/TotalSurplus',
                align: 'right',
                render: (text, data) => (
                    <span>{data.TotalTake+'/'+ data.TotalSurplus}</span>
                )
            },
            {
                title: '已使用',
                dataIndex: 'TotalUsed',
                key: 'TotalUsed',
                align: 'right'
            },
            {
                title: '状态',
                dataIndex: 'StatusName',
                key: 'StatusName',
            },
            {
                title: '操作',
                key: 'action',
                align: 'right',
                width: 150,
                render: (text, data) => {
                    return (
                        <span>
                            <span>
                                <a onClick={()=>this.clickExtension(data.Id, data)}>推广</a>
                                <Divider type="vertical" />
                            </span>
                            <span>
                                <a onClick={()=> this.clickEdit(data.Id)}>编辑</a>
                                <Divider type="vertical" />
                            </span>
                            {data.Status===2?<span>删除</span>:
                            <Popconfirm
                                title="确认删除?"
                                okText="确认"
                                cancelText="取消"
                                onConfirm={() => this.delete(data.Id)}
                            ><a>删除</a></Popconfirm>}
                        </span>
                    )
                }
            },
          ]
        const {dataSource, loading, valueLoading} = this.state;
        return(
            <Spin spinning={loading}>
                <Card bordered={false}>
                    <Button type="primary" onClick={this.addCoupon}>新增优惠券</Button>
                    <div style={{
                            background:'#fafafa',
                            marginBottom:16,
                            paddingTop:16,
                            paddingRight:16,
                            boxSizing:'border-box',
                            marginTop: 16
                        }}>
                        <div className="tableListForm">{this.renderForm()}</div>
                    </div>
                    <div className={styles.tableBox}>
                        <Spin spinning={valueLoading}>
                            <Table
                                columns={columns}
                                dataSource ={dataSource}
                                rowKey={record => record.Id}
                                onChange={this.onTableChange}
                                pagination={this.state.paginationProps}
                            />
                        </Spin>
                    </div>
                </Card>
                <Extension
                    ref={e => {
                        this.extension = e;
                    }}
                />
        </Spin>
        )
    }
}

export default connect(({ marketing,global, loading }) => ({
    marketing,
    oemInfo:global.oemInfo,
  }))(CouponComponent)
